﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CDSBDemandControl.Presenter;
using CDSBDemandControl.Model;
using System.Data;

namespace CDSBDemandControl.View.Web.PaginasInternas
{
    public partial class NewAlocacao : System.Web.UI.Page, IDiscriminatorDemand
    {
        private Presenter.DiscriminatorDemand Presenter;
        public string caption = "Previsão de Alocação referente ao mês {0}.";

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetExpires(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!this.IsPostBack || this.Session["Presenter"] == null)
            {
                this.Presenter = new DiscriminatorDemand(this);

                this.Session["Presenter"] = this.Presenter;

                if (!this.IsPostBack)
                    this.ListarAlocacao();
            }
            else
            {
                this.Presenter = (Presenter.DiscriminatorDemand)this.Session["Presenter"];
                this.Presenter.ResetView(this);
            }
        }

        private void ListarAlocacao()
        {
            this.Presenter.ListarPrevisaoAlocacao();
        }

        void IDiscriminatorDemand.ExibirAlocacao(IEnumerable<DemandModel> demandModels)
        {
            DateTime inicioPeriodo = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
               
            this.ExibirObservacao(string.Format(caption, inicioPeriodo.ToString("MMM/yyyy")));
            
            demandModels = 
                demandModels.ToList().FindAll(delegate(DemandModel d) 
                {
                    return inIntervalo(d.EstimatedStart, d.EstimatedConclude, inicioPeriodo);
                }
            );

            demandModels = demandModels.OrderBy(x => x.ID).ToList();

            this.AgruparTasksPorTeamProject(demandModels,inicioPeriodo);

            DataTable dt = new DataTable("demandas");
            dt.Columns.Add("ID");

            for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
            {
                dt.Columns.Add(""+i);
            }

            DataRow row = null;
            foreach (DemandModel model in demandModels)
            {
                row = dt.NewRow();
                row["ID"] = model.ID;

                for (int i = 1; i <= System.DateTime.DaysInMonth(inicioPeriodo.Year, inicioPeriodo.Month); i++)
                {
                    row[i] = inIntervalo(model.EstimatedStart, model.EstimatedConclude, inicioPeriodo.AddDays(i - 1)) ? "8h": string.Empty;
                }

                dt.Rows.Add(row);
            }

            gridDemandas.DataSource = dt;
            gridDemandas.DataBind();

        }

        private void AgruparTasksPorTeamProject(IEnumerable<DemandModel> demandModels, DateTime tmStart)
        {
            List<string> teamProjects = new List<string>() { "TeamProjectsSinacor", "TeamProjectsIMercado", "TeamProjectsSiteBVMF" };

            foreach (string str in teamProjects)
            {
                var demandGroups =
                       from d in demandModels
                       where (
                                    this.Presenter.CheckExistsWithin(d.Project, str)
                                    &&
                                    this.inIntervalo(d.EstimatedStart, d.EstimatedConclude, tmStart)
                                    &&
                                    d.State != "Cancelada"
                                )
                                ||
                                (
                                    (d.State == "Cancelada" && d.UsedHours != 0)
                                    &&
                                    (this.Presenter.CheckExistsWithin(d.Project, str))
                                    &&
                                    (this.inIntervalo(d.EstimatedStart, d.EstimatedConclude, tmStart))
                                )

                       group d by d.Project into g
                       select new { Project = g.Key, Demands = g };

                int subGroups = demandGroups.ToList().Count;

                for (int i = 0; i < subGroups; i++)
                {
                    this.CarregarConteudoMensal(demandGroups.ToList()[i].Demands, tmStart, str, feriados);
                    this.parentDiv.Controls.Add(new LiteralControl("<br />"));
                }
            }
        }

        private void ExibirObservacao(string obs)
        {
            this.LblObsOrdenacao.Text = obs;
            this.LblObsOrdenacao.Visible = this.LblObsOrdenacao.Text.Length > 0 ? true : false;
        }

        private bool inIntervalo(DateTime? EstimatedStart, DateTime? EstimatedConclude, DateTime tmStart)
        {
            //inicio
            bool porInicio =
                (EstimatedStart.Value.Date <= tmStart.Date && EstimatedConclude.Value.Date >= tmStart.Date);

            //final
            bool porFinal =
                (EstimatedStart.Value.Date >= tmStart.Date && tmStart.Month == EstimatedStart.Value.Month);

            return (porInicio || porFinal);
        }

        #region IDiscriminatorDemand Members

        void IDiscriminatorDemand.ExibirFila(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirEsteira(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirRanking(IEnumerable<CDSBDemandControl.Model.DeveloperModel> developers, IEnumerable<CDSBDemandControl.Model.DeveloperModel> leaders, IEnumerable<CDSBDemandControl.Model.DeveloperModel> focalpoints)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAtrasos(IEnumerable<CDSBDemandControl.Model.DemandModel> PendingDemands, IEnumerable<CDSBDemandControl.Model.DemandModel> Concludeddemands)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFaturamento(List<CDSBDemandControl.Model.BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirCodeReview(IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithCodeReview, IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithoutCodeReview)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirListaDisp(IEnumerable<CDSBDemandControl.Model.DemandModel> list, IEnumerable<CDSBDemandControl.Model.DeveloperModel> modelAusencias, List<DateTime> fer)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducaoUltimoMes(List<CDSBDemandControl.Model.DemandModel> BugList)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryWaitingList(List<CDSBDemandControl.Model.BillingModel> Billing, bool AllowsShow)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryProductionList(List<BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirSolicitacoesSites(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirManagementTeamTasks(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
